<?php
namespace app\common\service;

use app\common\models\AdminUser;
use think\Request;
use think\Session;

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/9/18
 * Time: 22:07
 */
class AdminLogin
{

    public $sessionName = "adminUserInfo";
    public $adminHomePage = "/admin";
    public $adminLoginPage = "/admin/publics/login";

    /**
     * @param $userName
     * @param $password
     * @return array
     */
    public function adminUserLogin($userName,$password){

        $adminUser = new AdminUser();

        $userInfo = $adminUser->getOneByLogin($userName);
        if (is_null($userInfo)){
            return ['status'=>false, 'message'=>'用户不存在'];
        }
        //状态是否正常
        if ($userInfo['status'] != 1){
            return ['status'=>false, 'message'=>'用户状态异常'];
        }
        //密码是否正确
        if (!$adminUser->checkPassword($password,$userInfo['password'])){
            return ['status'=>false, 'message'=>'密码错误'];
        }
        Session::set($this->sessionName,$userInfo->toArray());
        $adminUser->updateLogin($userInfo,[
            'id' => $userInfo['id'],
            'login_num' => $userInfo['login_num'] + 1,
            'last_login_time' => date('Y-m-d H:i:s'),
            'last_login_ip' => Request::instance()->ip()
        ]);

        return ['status'=>true];
    }

    /**
     * 清理session
     * @return void
     */
    public function clearSession(){
        Session::delete($this->sessionName);
        Session::flush();
    }

    /**
     * 判断是否登陆
     * @return bool
     */
    public function checkLogin(){
        if (Session::has($this->sessionName)){
            return true;
        }
        return false;
    }

    /**
     * 获取用户信息Session
     * @return array
     */
    public function getUserInfo(){
        return Session::get($this->sessionName);
    }

    /**
     * 获取用户IdSession
     * @return array
     */
    public function getUid(){
        $session = Session::get($this->sessionName);
        if (isset($session['id'])){
            return $session['id'];
        }else{
            return 0;
        }
    }
}